package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author Gareth Cao
 * @date 2022/5/1 20:36
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送验证码
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //根据发来的手机号查询该用户是否被禁用
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(user.getPhone()), "phone", user.getPhone());
        User u = userService.getOne(queryWrapper);
        if (u != null) {
            if (u.getStatus() == 0) {
                //该用户存在且禁用中,不发送验证码
                return R.error("该用户禁用中");
            }
        }

        //生成验证码并发送到手机中
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        log.info("验证码为: {}", code);
        //阿里云短信发送业务
        //SmsUtil.sendMessage(user.getPhone(), code.toString());
        //将验证码存到session中,以便之后校验
        request.getSession().setAttribute("验证码", code.toString());
        return R.success("发送验证码成功");
    }

    /**
     * 登录验证
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        //将验证码进行比较
        boolean flag = StringUtils.equals((String) session.getAttribute("验证码"), map.get("code"));
        if (!flag) {
            return R.error("您的验证码输入错误");
        }
        //验证成功,消除session中code
        session.removeAttribute("验证码");
        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(map.get("phone")), "phone", map.get("phone"));
        User user = userService.getOne(queryWrapper);
        if(user == null){
            //不new一个对象的话,调用set方法会出现空指针异常
            user = new User();
            user.setPhone(map.get("phone"));
            //不设置就默认为0,禁用该用户
            user.setStatus(1);
            userService.save(user);
        }
        //该用户存在,将用户id存到session中,其他页面根据userId来证明已经登录
        session.setAttribute("userId",user.getId());
        return R.success(user);
    }
}
